<template>
    <el-form :inline="true" :model="formInline" class="demo-form-inline" ref="ruleFormRef">
        <el-form-item label="名称：" prop="user">
            <el-input v-model="formInline.user" placeholder="请输入用户名" />
        </el-form-item>
        <div class="block">
            <el-form-item prop="region">
                <span class="demonstration">创建时间：</span>
                <el-date-picker v-model="formInline.region" type="daterange" range-separator="～"
                    start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD" />
            </el-form-item>
        </div>
        <el-form-item>
            <el-button type="primary" @click="search()">搜索</el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
    </el-form>
    <div class="botton-group">
        <el-dropdown trigger="click">
            <span class="el-dropdown-link">
                <el-button type="primary" plain @click="">新增</el-button>
            </span>
            <template #dropdown>
                <el-dropdown-menu>
                    <el-dropdown-item @click="addMenu1()">菜单</el-dropdown-item>
                    <el-dropdown-item @click="buttonGo()">按钮</el-dropdown-item>
                </el-dropdown-menu>
            </template>
        </el-dropdown>
        <el-button plain @click="delect()">删除</el-button>
        <el-button plain>更多操作</el-button>
    </div>
    <el-table :data="state.menuData" style="width: 100%; margin-bottom: 20px" row-key="key" :tree-props="defaultProps"
        @selection-change="handleSelectionChange" height="550">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="text" label="名字" sortable fixed="left" width="140" />
        <el-table-column prop="icon" label="图标">
            <template #default="data">
                <el-icon>
                    <div style="margin: 10px;">
                        <i class="iconfont" :class="`Myicon-${data.row.icon}`"></i>
                    </div>
                </el-icon>
            </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" sortable :filters="[
          { text: '菜单', value: '0' },
          { text: '按钮', value: '1' },
        ]" :filter-method="filterTag" filter-placement="bottom-end">
            <template #default="scope">
                <el-tag :type="scope.row.type === '1' ? 'info' : ''" disable-transitions>
                    {{scope.row.type==1?'按钮':'菜单'}}</el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="path" label="地址" />
        <el-table-column prop="component" label="Vue组件" width="150" />
        <el-table-column prop="permission" label="权限" sortable>
            <template #default="scope">{{scope.row.permission==null?'无': scope.row.permission}}</template>
        </el-table-column>
        <el-table-column prop="order" label="排序" sortable />
        <el-table-column prop="createTime" label="创建时间" sortable width="180" />
        <el-table-column prop="modifyTime" label="修改时间" sortable width="180">
            <template #default="scope">{{scope.row.modifyTime==null?'从未修改': scope.row.modifyTime}}</template>
        </el-table-column>
        <el-table-column prop="text" label="操作" fixed="right">
            <template #default="scope">
                <el-button :icon="Edit" circle @click="handleEdit(scope.$index, scope.row)" />
            </template>
        </el-table-column>
    </el-table>

    <el-dialog v-model="dialogFormVisible" title="新增菜单">
        <el-dialog v-model="innerVisible" width="30%" title="请选择菜单图标：" append-to-body>
            <el-icon>
                <i style="display: inline-block;" v-for="item in icongroup" class="iconfont" :class="`Myicon-${item}`"
                    @click="getIcon(item)"></i>
            </el-icon>
        </el-dialog>
        <el-form :model="form" ref="ruleFormRef2">
            <el-form-item label="菜单名称：" :label-width="formLabelWidth">
                <el-input v-model="form.menuName" autocomplete="off" />
            </el-form-item>
            <el-form-item label="菜单URL：" :label-width="formLabelWidth">
                <el-input v-model="form.path" autocomplete="off" />
            </el-form-item>
            <el-form-item label="组件地址：" :label-width="formLabelWidth">
                <el-input v-model="form.component" autocomplete="off" />
            </el-form-item>
            <el-form-item label="相关权限：" :label-width="formLabelWidth">
                <el-input v-model="form.perms" autocomplete="off" />
            </el-form-item>
            <el-form-item label="菜单图标：" :label-width="formLabelWidth">
                <el-input v-model="form.icon" placeholder="点击右侧按钮选择图标" class="input-with-select">
                    <template #append>
                        <el-button :icon="Setting" @click="innerVisible = true" />
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item label="菜单排序：" style="margin-left: 57px;">
                <el-input-number v-model="form.orderNum" class="mx-4" :min="1" controls-position="right"
                    @change="handleChange" />
            </el-form-item>
            <div class="account-list">
                <div>
                    <p style="margin: 10px 10px;">上级菜单：</p>
                    <el-tree :data="state.menuData" :props="defaultProps1" show-checkbox check-strictly ref="treeRef"
                        node-key="key" style="overflow-y: auto;height: 130px;">
                    </el-tree>
                </div>
            </div>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="realGo()">提交</el-button>
            </span>
        </template>
    </el-dialog>

    <el-dialog v-model="dialogTableVisible" title="新增按钮">
        <el-dialog v-model="innerVisible1" width="30%" title="请选择菜单图标：" append-to-body>
            <el-icon>
                <i style="display: inline-block;" v-for="item in icongroup" class="iconfont" :class="`Myicon-${item}`"
                    @click="getIcon(item)"></i>
            </el-icon>
        </el-dialog>
        <el-form :model="form1">
            <el-form-item label="按钮名称：" :label-width="formLabelWidth">
                <el-input v-model="form1.menuName" autocomplete="off" />
            </el-form-item>
            <el-form-item label="相关权限：" :label-width="formLabelWidth">
                <el-input v-model="form1.perms" autocomplete="off" />
            </el-form-item>
            <div class="account-list">
                <div>
                    <p style="margin: 10px 10px;">上级菜单：</p>
                    <el-tree :data="state.menuData" :props="defaultProps1" show-checkbox check-strictly ref="treeRef"
                        node-key="key" style="overflow-y: auto;height: 130px;">
                    </el-tree>
                </div>
            </div>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogTableVisible = false">取消</el-button>
                <el-button type="primary" @click="BtnGo()">提交</el-button>
            </span>
        </template>
    </el-dialog>

    <el-dialog v-model="dialogFormVisible1" title="修改菜单">
        <el-dialog v-model="innerVisible" width="30%" title="请选择菜单图标：" append-to-body>
            <el-icon>
                <i style="display: inline-block;" v-for="item in icongroup" class="iconfont" :class="`Myicon-${item}`"
                    @click="getIcon(item)"></i>
            </el-icon>
        </el-dialog>
        <el-form :model="form2">
            <el-form-item label="菜单名称：" :label-width="formLabelWidth">
                <el-input v-model="form2.menuName" autocomplete="off" />
            </el-form-item>
            <el-form-item label="菜单URL：" :label-width="formLabelWidth">
                <el-input v-model="form2.path" autocomplete="off" />
            </el-form-item>
            <el-form-item label="组件地址：" :label-width="formLabelWidth">
                <el-input v-model="form2.component" autocomplete="off" />
            </el-form-item>
            <el-form-item label="相关权限：" :label-width="formLabelWidth">
                <el-input v-model="form2.perms" autocomplete="off" />
            </el-form-item>
            <el-form-item label="菜单图标：" :label-width="formLabelWidth">
                <el-input v-model="form2.icon" placeholder="点击右侧按钮选择图标" class="input-with-select">
                    <template #append>
                        <el-button :icon="Setting" @click="innerVisible = true" />
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item label="菜单排序：" style="margin-left: 57px;">
                <el-input-number v-model="form2.orderNum" class="mx-4" :min="1" :max="10" controls-position="right"
                    @change="handleChange" />
            </el-form-item>
            <div class="account-list">
                <div>
                    <p style="margin: 10px 10px;">上级菜单：</p>
                    <el-tree :data="state.menuData" :props="defaultProps1" show-checkbox check-strictly ref="treeRef"
                        node-key="key" style="overflow-y: auto;height: 130px;">
                    </el-tree>
                </div>
            </div>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogFormVisible1 = false">取消</el-button>
                <el-button type="primary" @click="realChange()">提交</el-button>
            </span>
        </template>
    </el-dialog>

    <el-dialog v-model="dialogFormVisible2" title="修改按钮">
        <el-dialog v-model="innerVisible" width="30%" title="请选择菜单图标：" append-to-body>
            <el-icon>
                <i style="display: inline-block;" v-for="item in icongroup" class="iconfont" :class="`Myicon-${item}`"
                    @click="getIcon(item)"></i>
            </el-icon>
        </el-dialog>
        <el-form :model="form2">
            <el-form-item label="按钮名称：" :label-width="formLabelWidth">
                <el-input v-model="form2.menuName" autocomplete="off" />
            </el-form-item>
            <el-form-item label="相关权限：" :label-width="formLabelWidth">
                <el-input v-model="form2.perms" autocomplete="off" />
            </el-form-item>
            <div class="account-list">
                <div>
                    <p style="margin: 10px 10px;">上级菜单：</p>
                    <el-tree :data="state.menuData" :props="defaultProps1" show-checkbox check-strictly ref="treeRef"
                        node-key="key" style="overflow-y: auto;height: 130px;">
                    </el-tree>
                </div>
            </div>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogFormVisible1 = false">取消</el-button>
                <el-button type="primary" @click="realChange()">提交</el-button>
            </span>
        </template>
    </el-dialog>

    <el-dialog v-model="dialogVisible" title="删除确认" width="30%">
        <span>你确定要删除以下内容吗？如果其包含子记录，也将一并删除！
            <p style="margin-top: 10px;">{{state.delname.toString()}}</p>
        </span>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="realDel()">确定</el-button>
            </span>
        </template>
    </el-dialog>

</template>

<script setup lang="ts">
import {
    Edit,
    Setting,
    Search
} from '@element-plus/icons-vue'
import { onMounted, reactive, ref } from 'vue';
import { FormInstance, ElTable, ElTree, ElMessage } from 'element-plus'
import { getMenuApi, addMenu, delMenu, changeMenu } from '../../apis/menu'
import { fromPairs } from 'lodash';
const ruleFormRef = ref<FormInstance>()
const ruleFormRef2 = ref<FormInstance>()
const formInline = reactive({
    user: '',
    region: '',
})

const state = reactive({
    menuData: [] as any,
    delId: '',
    delname: '',
})

interface User {
    id: number
    date: string
    name: string
    hasChildren?: boolean
    children?: User[]
}

const treeRef = ref<InstanceType<typeof ElTree>>()
const innerVisible = ref(false)
const innerVisible1 = ref(false)
const innerVisible2 = ref(false)

const defaultProps = {
    children: state.menuData.children,
    hasChildren: "true"
}

const defaultProps1 = {
    children: state.menuData.children,
    label: "title"
}

const form = reactive({
    menuName: '',
    path: '',
    component: '',
    parentId: '' as any,
    icon: '',
    orderNum: 1,
    perms: '',
    type: '',
})

const form1 = reactive({
    menuName: '',
    path: '',
    component: '',
    parentId: '' as any,
    icon: '',
    orderNum: 1,
    perms: '',
    type: '',
})

const form2 = reactive({
    menuName: '',
    path: '',
    component: '',
    parentId: '' as any,
    icon: '',
    orderNum: 1,
    perms: '',
    type: '',
    menuId: ''
})

const dialogTableVisible = ref(false)
const dialogFormVisible = ref(false)
const dialogFormVisible1 = ref(false)
const dialogFormVisible2 = ref(false)
const formLabelWidth = '140px'
const multipleSelection = ref<User[]>([])
const dialogVisible = ref(false)

const handleChange = (value: number) => {
    console.log(value)
}

const icongroup = ref(["areachart", "piechart", "bar-chart", "dot-chart", "line-chart", "radar-chart", "heatmap", "fall", "rise", "stock", "boxplot", "fund", "sliders"])

const resetForm = (ruleForm: FormInstance | undefined) => {
    if (!ruleForm) return;
    ruleForm.resetFields();
    getAllMenu()
};

const filterTag = (value: string, row: any) => {
    return row.type === value
}

const handleEdit = (index: number, row: any) => {
    console.log(index, row)
    if (row.type == 0) {
        dialogFormVisible1.value = true
    }
    else {
        dialogFormVisible2.value = true
    }
    form2.menuName = row.title
    form2.path = row.path
    form2.component = row.component
    form2.parentId = row.parentId
    form2.icon = row.icon
    form2.perms = row.permission
    form2.menuId = row.id
    form2.type = row.type
    setTimeout(() => {
        setCheckedKeys(row.parentId.split())
    }, 500);
    console.log(row.parentId.split());

    form2.orderNum = row.orderNum.push(row.orderNum)
}

const getCheckedKeys = () => {
    console.log(treeRef.value!.getCheckedKeys(false))
    form.parentId = treeRef.value!.getCheckedKeys(false)
    form1.parentId = treeRef.value!.getCheckedKeys(false)
}

const setCheckedKeys = (data: any) => {
    treeRef.value!.setCheckedKeys(data, false)
}

const handleSelectionChange = (val: User[]) => {
    multipleSelection.value = val
}

function search() {
    const a = `menuName=${formInline.user}&createTimeFrom=${formInline.region[0]}&createTimeTo=${formInline.region[1]}&`
    console.log(typeof formInline.user);

    getAllMenu(a)

}

function addMenu1() {
    dialogFormVisible.value = true
    form.type = "0"
}

async function getAllMenu(data?: any) {
    const res = await getMenuApi(data)
    console.log(res);
    state.menuData = res.rows.children

}

function getIcon(data: any) {
    form.icon = data
    innerVisible.value = false
}

async function addOneMenu() {
    //菜单
    const a = `menuName=${form.menuName}&path=${form.path}&component=${form.component}&parentId=${form.parentId}&icon=${form.icon}&orderNum=${String(form.orderNum)}&perms=${form.perms}&type=${form.type}`
    //按钮
    const b = `menuName=${form1.menuName}&parentId=${form1.parentId}&type=1`

    if (form.type == "0") {
        const res = await addMenu(a)
        console.log(res);
        if (res == "") {
            ElMessage.success("菜单添加成功")
            getAllMenu()
        }
        console.log("菜单添加成功");
        form.type = ""

    }
    else {
        const res = await addMenu(b)
        console.log(res);
        if (res == "") {
            ElMessage.success("按钮添加成功")
            dialogTableVisible.value = false
            getAllMenu()
        }
        console.log("按钮添加成功");
        console.log(form1.parentId);

    }
}

async function delById(id: any) {
    const res = await delMenu(id)
    console.log(res);
    if (res == "") {
        ElMessage.success("删除成功")
        dialogVisible.value = false
        getAllMenu()
    }
}

async function changeM() {
    const a = `menuName=${form2.menuName}&path=${form2.path}&component=${form2.component}&parentId=${form2.parentId}&icon=${form2.icon}&orderNum=${String(form2.orderNum)}&perms=${form2.perms}&type=${form2.type}&menuId=${form2.menuId}`
    const res = await changeMenu(a)
    console.log(res);
    if (res == "") {
        ElMessage.success("修改成功")
        getAllMenu()
    }
}
function realGo() {
    getCheckedKeys()
    addOneMenu()
    dialogFormVisible.value = false
}

function buttonGo() {
    dialogTableVisible.value = true

}
function BtnGo() {
    getCheckedKeys()
    addOneMenu()

}
function realChange() {
    dialogFormVisible1.value = false
    dialogFormVisible2.value = false
    changeM()
}
function delect() {
    const data = JSON.parse(JSON.stringify(multipleSelection.value));
    console.log(data);
    const a = data.map((item: { title: any }) => {
        return item.title
    })
    state.delId = a
    const b = data.map((item: { id: any }) => {
        return item.id
    })
    state.delname = a
    state.delId = b
    console.log(a);
    console.log(b);
    if (data != "") {
        dialogVisible.value = true
    } else {
        ElMessage.error("没有选中任何内容，无法删除")
    }


}
function realDel() {
    delById(state.delId)
}
onMounted(() => {
    getAllMenu()
    // getCheckedKeys()
})
</script>

<style scoped lang="less">
.demo-form-inline {
    display: flex;
}

.el-dropdown-link {
    margin-right: 10px;
}

.el-input-number {
    width: 100%;
}

.account-list {
    margin-left: 50px;
}

.el-icon {
    width: 90%;

    .iconfont {
        margin: 10px;
    }
}
</style>